<template>
  <view class="currency-selector-mask" v-if="show" @click="onMaskClick">
    <view class="currency-selector-popup" @click.stop>
      <!-- 标题栏 -->
      <view class="selector-header">
        <text class="header-title">选择货币</text>
        <text class="header-close" @click="onClose">取消</text>
      </view>
      
      <!-- 货币类型切换 -->
      <view class="currency-type-tabs">
        <view 
          class="type-tab" 
          :class="{ active: currentType === 'crypto' }"
          @click="switchType('crypto')"
        >
          <text>数字货币</text>
        </view>
        <view 
          class="type-tab" 
          :class="{ active: currentType === 'legal' }"
          @click="switchType('legal')"
        >
          <text>合法货币</text>
        </view>
      </view>
      
      <!-- 货币列表（新增图标、选中状态、合法货币符号） -->
      <view class="currency-list">
        <!-- 列表项：适配两种货币结构 -->
        <view 
          class="currency-item" 
          v-for="(currency, index) in filteredCurrencies" 
          :key="index"
          @click="onSelectCurrency(currency)"
          v-if="currency"
        >
          <!-- 货币图标（智能适配两种货币类型） -->
          <view class="currency-icon-wrap">
            <image 
              class="currency-icon" 
              :src="getCurrencyIcon(currency)" 
              mode="aspectFit"
              @error="handleIconError($event, currency)"
            />
          </view>
          
          <!-- 货币信息（统一字段映射） -->
          <view class="currency-info">
            <view class="currency-code-wrap">
              <!-- 货币代码：统一使用displayCode字段 -->
              <text class="currency-code">{{ currency.displayCode || currency.nameEn || currency.code }}</text>
              <!-- 合法货币显示符号（如$、¥） -->
              <text class="currency-symbol" v-if="currency.displaySymbol || currency.symbol">
                {{ currency.displaySymbol || currency.symbol }}
              </text>
            </view>
            <!-- 货币名称：统一使用displayName字段 -->
            <text class="currency-name">{{ currency.displayName || currency.nameZh || currency.title || currency.name }}</text>
          </view>
          
          <!-- 选中状态图标（明确当前选择） -->
          <image 
            class="selected-icon" 
            src="/static/images/selected.png"
            mode="aspectFit"
            v-if="isSelected(currency)"
          />
        </view>
        
        <!-- 加载中状态 -->
        <view class="loading" v-if="loading">
          <view class="loading-spinner"></view>
    
        </view>
        
        <!-- 无数据状态 -->
        <view class="no-data" v-if="!loading && filteredCurrencies.length === 0">
          <image src="/static/images/no-data.png" mode="aspectFit" class="no-data-icon" />
          <text class="no-data-text">暂无相关货币</text>
        </view>
        
        <!-- 无更多数据提示 -->
        <view class="no-more" v-if="!loading && ((currentType === 'crypto' && !hasMoreCrypto && cryptoCurrencies.length > 0) || (currentType === 'legal' && !hasMoreLegal && legalCurrencies.length > 0))">
          <text>没有更多货币了</text>
        </view>
        
        <!-- 触发加载更多的占位元素 -->
        <view class="loading-trigger"></view>
      </view>
    </view>
  </view>
</template>

<script>
import { gettickers } from '@/api/user.js';

export default {
  components: {
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    selectorType: {
      type: String,
      default: 'source' // source=源货币，target=目标货币
    },
    // 父组件传入已选中的货币（替代$parent，降低耦合）
    selectedCurrency: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      currentType: 'crypto', // 当前类型：crypto=数字货币，legal=合法货币
      cryptoCurrencies: [],  // 数字货币列表
      legalCurrencies: [],   // 合法货币列表
      searchKeyword: '',     // 保留搜索字段（避免computed报错，可删除）
      // 分页参数
      cryptoPage: 1,
      legalPage: 1,
      pageSize: 20,
      loading: false,
      hasMoreCrypto: true,
      hasMoreLegal: true,
      defaultIcon: '/static/images/default-currency.png' // 图标加载失败兜底
    };
  },
  computed: {
    // 当前类型对应的货币列表
    currentCurrencies() {
      if (this.currentType === 'crypto') {
        return this.cryptoCurrencies || [];
      } else {
        return this.legalCurrencies || [];
      }
    },
    // 过滤列表（保留结构，无搜索则返回原列表）
    filteredCurrencies() {
      const currencies = this.currentCurrencies || [];
      if (!this.searchKeyword) return currencies;
      const keyword = this.searchKeyword.toLowerCase();
      return currencies.filter(currency => {
        if (!currency) return false;
        // 搜索匹配：代码（nameEn/code）或名称（nameZh/title）
        const code = (currency.displayCode || currency.nameEn || currency.code || '').toLowerCase();
        const name = (currency.displayName || currency.nameZh || currency.title || currency.name || '').toLowerCase();
        return code.includes(keyword) || name.includes(keyword);
      });
    }
  },
  watch: {
    // 弹窗显示时加载初始数据
    show(newVal) {
      if (newVal) {
        // 重新初始化滚动监听
        this.$nextTick(() => {
          this.initScrollListener();
        });
        this.loadInitialData();
      } else {
        this.searchKeyword = ''; // 隐藏时重置搜索
        
        // 断开IntersectionObserver连接
        if (this._scrollObserver) {
          this._scrollObserver.disconnect();
        }
      }
    },
    // 切换类型时加载对应数据
    currentType(newVal) {
      // 重置滚动位置
      const listEl = uni.createSelectorQuery().in(this).select('.currency-list');
      if (listEl) {
        listEl.scrollOffset(data => {
          if (data && data.scrollTop > 0) {
            // 平滑滚动到顶部
            uni.pageScrollTo({
              scrollTop: 0,
              duration: 300
            });
          }
        }).exec();
      }
      
      // 切换类型时重新初始化滚动监听
      this.$nextTick(() => {
        this.initScrollListener();
      });
      
      if ((newVal === 'crypto' && this.cryptoCurrencies.length === 0) || 
          (newVal === 'legal' && this.legalCurrencies.length === 0)) {
        this.loadInitialData();
      }
    }
  },
  mounted() {
    // 挂载时初始化滚动监听
    this.initScrollListener();
  },
  
  // 销毁前清理
  beforeDestroy() {
    // 销毁IntersectionObserver，防止内存泄漏
    if (this._scrollObserver) {
      this._scrollObserver.disconnect();
    }
  },
  methods: {
    // 初始化滚动监听（上拉加载更多）
    initScrollListener() {
      // 使用自定义滚动监听而不是全局页面滚动
      this.$nextTick(() => {
        const listSelector = '.currency-list';
        const observer = uni.createIntersectionObserver(this);
        
        // 创建滚动触发区域（底部加载区）
        const loadTrigger = '.loading-trigger';
        
        // 监听底部触发区域是否可见
        observer.relativeTo(listSelector).observe(loadTrigger, (res) => {
          // 当底部触发区域可见且不在加载中，触发加载更多
          if (res.intersectionRatio > 0 && !this.loading && this.show) {
            console.log('触发区域可见度:', res.intersectionRatio);
            this.loadMore();
          }
        });
        
        // 保存观察者实例以便后续清理
        this._scrollObserver = observer;
      });
    },
    
    // 切换货币类型
    switchType(type) {
      if (this.currentType === type) return;
      this.currentType = type;
    },
    
    // 加载初始数据（首次显示/切换类型无数据时）
    loadInitialData() {
      if (this.currentType === 'crypto') {
        this.loadCryptoCurrencies();
      } else {
        this.loadLegalCurrencies();
      }
    },
    
    // 加载数字货币（适配nameEn/nameZh/icon字段）
    async loadCryptoCurrencies() {
      if (this.loading || !this.hasMoreCrypto) return;
      this.loading = true;

      try {
        const params = {
          param: {
            action: "currency",
            "data[page]": this.cryptoPage,
            "data[limit]": this.pageSize
          },
          c: "app",
          m: "v2"
        };

        const result = await gettickers(params);
        // 校验接口返回（适配实际数据路径：result.data.data.list）
        if (!result || !result.success || !result.data?.data?.list) {
          throw new Error('数据获取失败');
        }

        const newCurrencies = result.data.data.list.map(item => ({
          ...item,
          type: 0, // 数字货币类型标记
          id: item.id || item.nameEn || `crypto_${Date.now()}_${Math.random()}`, // 确保唯一ID
          icon: this.ensureHttps(item.icon) || this.defaultIcon, // 图标字段，确保HTTPS
          // 统一字段映射：数字货币使用nameEn和nameZh
          code: item.nameEn, // 货币代码（BTC、ETH等）
          name: item.nameZh, // 货币中文名称
          displayCode: item.nameEn, // 显示用代码
          displayName: item.nameZh // 显示用名称
        }));

        // 合并数据（避免覆盖）
        this.cryptoCurrencies = [...this.cryptoCurrencies, ...newCurrencies];
        this.cryptoPage++;
        // 判断是否还有更多数据
        this.hasMoreCrypto = newCurrencies.length >= this.pageSize;

      } catch (error) {
        console.error('加载数字货币出错:', error);
        uni.showToast({ title: '数字货币加载失败', icon: 'none', duration: 1500 });
      } finally {
        this.loading = false;
      }
    },
    
    // 加载合法货币（适配code/title/logo/symbol字段）
    async loadLegalCurrencies() {
      if (this.loading || !this.hasMoreLegal) return;
      this.loading = true;

      try {
        const params = {
          param: {
            action: "legalTender",
            "data[page]": this.legalPage,
            "data[limit]": this.pageSize
          },
          c: "app",
          m: "v2"
        };

        const result = await gettickers(params);
        // 校验接口返回（统一数据路径：result.data.data.list，避免原代码漏data层）
        if (!result || !result.success || !result.data?.data?.list) {
          throw new Error('数据获取失败');
        }

        const newCurrencies = result.data.data.list.map(item => ({
          ...item,
          type: 1, // 合法货币类型标记
          id: item.id || `legal_${Date.now()}_${Math.random()}`, // 确保唯一ID
          logo: this.ensureHttps(item.logo) || this.defaultIcon, // 图标字段，确保HTTPS
          // 统一字段映射：合法货币使用code和title
          name: item.title || item.name, // 货币中文名称
          displayCode: item.code, // 显示用代码（USD、CNY等）
          displayName: item.title || item.name, // 显示用名称
          displaySymbol: item.symbol || '' // 显示用符号（$、¥等）
        }));

        // 合并数据
        this.legalCurrencies = [...this.legalCurrencies, ...newCurrencies];
        this.legalPage++;
        // 判断是否还有更多数据
        this.hasMoreLegal = newCurrencies.length >= this.pageSize;

      } catch (error) {
        console.error('加载合法货币出错:', error);
        uni.showToast({ title: '合法货币加载失败', icon: 'none', duration: 1500 });
      } finally {
        this.loading = false;
      }
    },
    
    // 加载更多数据（防抖处理）
    loadMore: function() {
      console.log('触发加载更多', this.currentType);
      
      // 清除之前的定时器（防抖处理）
      if (this._loadMoreTimer) {
        clearTimeout(this._loadMoreTimer);
      }
      
      // 设置300ms延迟，防止频繁触发
      this._loadMoreTimer = setTimeout(() => {
        // 防止频繁触发
        if (this.loading) {
          console.log('正在加载中，跳过请求');
          return;
        }
        
        // 检查是否还有更多数据
        if (this.currentType === 'crypto' && !this.hasMoreCrypto) {
          console.log('数字货币没有更多数据');
          return;
        }
        
        if (this.currentType === 'legal' && !this.hasMoreLegal) {
          console.log('合法货币没有更多数据');
          return;
        }
        
        // 加载当前类型的更多数据
        if (this.currentType === 'crypto') {
          this.loadCryptoCurrencies();
        } else {
          this.loadLegalCurrencies();
        }
      }, 300);
    },
    
    // 确保URL使用HTTPS协议
    ensureHttps(url) {
      if (!url || typeof url !== 'string') return url;
      // 如果是http开头的地址，转换为https
      if (url.startsWith('http://')) {
        return url.replace('http://', 'https://');
      }
      return url;
    },
    
    // 获取货币图标（智能适配两种货币类型）
    getCurrencyIcon(currency) {
      if (!currency) return this.defaultIcon;
      // 数字货币优先使用icon字段，合法货币优先使用logo字段
      // 注意：URL转换已在数据加载时完成
      if (currency.type === 0) {
        return currency.icon || this.defaultIcon;
      } else {
        return currency.logo || currency.icon || this.defaultIcon;
      }
    },
    
    // 安全获取货币代码
    getCurrencyCode(currency) {
      if (!currency) return '';
      return currency.displayCode || currency.nameEn || currency.code || '';
    },
    
    // 安全获取货币名称
    getCurrencyName(currency) {
      if (!currency) return '';
      return currency.displayName || currency.nameZh || currency.title || currency.name || '';
    },
    
    // 安全获取货币符号
    getCurrencySymbol(currency) {
      if (!currency) return '';
      return currency.displaySymbol || currency.symbol || '';
    },
    
    // 图标加载失败处理（兜底显示默认图标）
    handleIconError(e, currency) {
      console.warn(`货币图标加载失败:`, currency);
      e.target.src = this.defaultIcon;
    },
    
    // 判断货币是否已选中（基于父组件传入的selectedCurrency）
    isSelected(currency) {
      // 增加安全检查
      if (!currency || !currency.id || !this.selectedCurrency || !this.selectedCurrency.id) {
        return false;
      }
      return this.selectedCurrency.id === currency.id;
    },
    
    // 选择货币（向父组件传递统一格式的数据）
    onSelectCurrency(currency) {
      // 增加安全检查
      if (!currency) {
        console.error('货币数据为空，无法选择');
        return;
      }
      
      // 确保有ID或生成一个临时ID
      const id = currency.id || `temp_${Date.now()}`;
      
      // 构建统一的货币数据格式，适配两种货币类型
      const unifiedCurrency = {
        id: id,
        type: currency.type || (currency.nameEn ? 0 : 1), // 0=数字货币，1=合法货币
        // 统一代码字段：数字货币用nameEn，合法货币用code
        code: this.getCurrencyCode(currency),
        // 统一名称字段：数字货币用nameZh，合法货币用title
        name: this.getCurrencyName(currency),
        // 统一图标字段：数字货币用icon，合法货币用logo
        icon: this.getCurrencyIcon(currency),
        // 合法货币特有的符号字段
        symbol: this.getCurrencySymbol(currency),
        // 保留原始数据，供调试和拓展使用
        _raw: currency
      };
      
      console.log('选中货币:', unifiedCurrency);
      this.$emit('select', unifiedCurrency);
      this.onClose(); // 选中后自动关闭弹窗
    },
    
    // 关闭弹窗
    onClose() {
      this.$emit('close');
    },
    
    // 点击遮罩层关闭
    onMaskClick() {
      this.onClose();
    }
  }
};
</script>

<style scoped>
/* 遮罩层样式 */
.currency-selector-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 999;
  backdrop-filter: blur(4px); /* 毛玻璃效果，提升视觉体验 */
}

/* 弹窗容器 */
.currency-selector-popup {
  width: 100%;
  background: #fff;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 -2px 15px rgba(0, 0, 0, 0.1);
}

/* 标题栏 */
.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 30rpx;
  border-bottom: 1px solid #f5f5f5;
}
.header-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #1a1a1a;
}
.header-close {
  font-size: 32rpx;
  color: #666;
  padding: 10rpx 15rpx;
  border-radius: 20rpx;
  transition: background 0.2s;
}
.header-close:hover {
  background: #f5f5f5;
}

/* 类型切换栏 */
.currency-type-tabs {
  display: flex;
  border-bottom: 1px solid #f5f5f5;
}
.type-tab {
  flex: 1;
  text-align: center;
  padding: 25rpx 0;
  font-size: 32rpx;
  color: #666;
  position: relative;
  transition: color 0.2s;
}
.type-tab.active {
  color: #007aff;
  font-weight: 500;
}
.type-tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 4rpx;
  background: #007aff;
}

/* 列表容器 */
.currency-list {
  height: calc(80vh - 200rpx); /* 调整高度，适配图标显示 */
  overflow-y: auto;
  background: #fafafa;
}

/* 列表项 */
.currency-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 30rpx;
  background: #fff;
  border-bottom: 1px solid #f5f5f5;
  transition: background 0.2s;
}
.currency-item:hover {
  background: #fafafa;
}

/* 货币图标容器 */
.currency-icon-wrap {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  overflow: hidden;
  background: #f5f5f5;
  margin-right: 20rpx;
  flex-shrink: 0; /* 防止图标被压缩 */
}
.currency-icon {
  width: 100%;
  height: 100%;
}

/* 货币信息 */
.currency-info {
  flex: 1; /* 占满剩余宽度 */
}
.currency-code-wrap {
  display: flex;
  align-items: center;
}
.currency-code {
  font-size: 34rpx;
  font-weight: 600;
  color: #1a1a1a;
}
.currency-symbol {
  font-size: 28rpx;
  color: #666;
}
.currency-name {
  font-size: 26rpx;
  color: #999;
  margin-top: 5rpx;
}

/* 选中图标 */
.selected-icon {
  width: 40rpx;
  height: 40rpx;
  margin-left: 10rpx;
}

/* 加载中状态 */
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
  color: #666;
}

/* 加载旋转器 */
.loading-spinner {
  width: 24rpx;
  height: 24rpx;
  border: 2rpx solid #f3f3f3;
  border-top: 2rpx solid #666;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  margin-left: 15rpx;
}

/* 无数据状态 */
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
  color: #999;
}
.no-data-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
  opacity: 0.5;
}
.no-data-text {
  font-size: 28rpx;
}

/* 无更多数据提示 */
.no-more {
  padding: 20rpx 0;
  text-align: center;
  color: #999;
  font-size: 24rpx;
  opacity: 0.8;
}

/* 触发加载更多的占位元素 */
.loading-trigger {
  height: 10rpx;
  width: 100%;
  /* 位于列表底部，但在视觉上不可见 */
  opacity: 0;
}
</style>